package com.mlf.observer.demo02;

import java.util.concurrent.Flow;

public class PriceSubscriber implements Flow.Subscriber<PriceChangeEvent> {

    private Flow.Subscription subscription;
    private final PriceChangeListener listener;

    public PriceSubscriber() {
        this.listener = (oldPrice, newPrice) -> {
            System.out.println("Default listener: Price changed from " + oldPrice + " to " + newPrice);
        };
    }

    public PriceSubscriber(PriceChangeListener listener) {
        this.listener = listener;
    }

    @Override
    public void onSubscribe(Flow.Subscription subscription) {
        this.subscription = subscription;
        subscription.request(Long.MAX_VALUE); // 请求无限数量的通知
    }

    @Override
    public void onNext(PriceChangeEvent event) {
        System.out.println("Price changed from " + event.getOldPrice() + " to: " + event.getNewPrice());
        if (listener != null) {
            // 现在可以传递正确的旧价格和新价格
            listener.onPriceChanged(event.getOldPrice(), event.getNewPrice());
        }
        // 不再请求新的项目，因为我们已经在onSubscribe中请求了无限数量

    }



    @Override
    public void onError(Throwable throwable) {
        System.err.println("Error: " + throwable.getMessage());
    }

    @Override
    public void onComplete() {
        System.out.println("Subscription completed");
    }
}
